<template>
  <a-card>
    <p style="font-size: 18px; text-align: center">采购入库退库详情</p>
    <br />

    <a-form-model :model="Form" v-bind="layout"
      ><!-- 顶部的信息  -->
      <a-row>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="单据号">
            <div>{{ Form.document }}</div>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="单据日期">
            <div>{{ Form.documentDate }}</div>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="供应商">
            <div>{{ Form.supplier_dictText }}</div>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="仓库名称">
            <div>{{ Form.storname }}</div>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="收发类别">
            <div>{{ Form.sendReceiveType_dictText }}</div>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="库存组织">
            <div>{{ Form.pkCalbodyByCode }}</div>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="业务类型">
            <div>{{ Form.cbiztype_dictText }}</div>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="库管员">
            <div>{{ Form.cwhsmanagerid }}</div>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <a-table
      :columns="columns"
      :data-source="DataSource"
      style="margin-top: 10px"
      :pagination="false"
      :scroll="autoSize"
    >
    </a-table>

    <div style="margin-top: 20px">
      <!-- 单据 -->
      <a-form-model :model="Form" v-bind="layout">
        <!-- 顶部的信息 -->
        <a-row>
          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="负责人">
              <div>{{ Form.responsiblePerson_dictText }}</div>
            </a-form-model-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="审核人">
              <div>{{ Form.inspector_dictText }}</div>
            </a-form-model-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="审核日期">
              <div>{{ Form.balance }}</div>
            </a-form-model-item>
          </a-col>

          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="制单人">
              <div>{{ Form.singleProducer_dictText }}</div>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>

      <!-- 提交按钮组  
      1. 能审核提交的人是不能点击保存的
      2. 能保存的人是不能审核和提交的
      -->
      <div style="margin-top: 20px">
        <center>
          <a-button type="primary" style="margin-right: 20px" @click="goPrint">
            打印
          </a-button>

          <a-button style="margin-right: 20px" disabled> 保存 </a-button>

          <a-button
            @click="Examine"
            style="margin-right: 20px"
            :disabled="!Form.canCheck"
          >
            审核
          </a-button>

          <a-button
            @click="No_Examine"
            style="margin-right: 20px"
            :disabled="Form.canCheck"
          >
            反审核
          </a-button>

          <a-button
            type="primary"
            @click="handleSaveButton"
            style="margin-right: 20px"
          >
            同步至用友
          </a-button>
        </center>
      </div>
    </div>

    <div style="display: none">
      <div id="printCons" style="width: 85%; margin: 0 auto; color: black">
        <!-- // 标题 -->
        <div
          id="style1"
          style="
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            height: 30px;
            line-height: 30px;
          "
        >
          <!-- 顶部的信息  -->
          <div style="margin-left: 10px">
            <div>单据号: {{ Form.document }}</div>
          </div>
          <div style="margin-left: 15px">
            <div>日期: {{ Form.documentDate }}</div>
          </div>
          <div style="margin-left: 15px">
            <div>仓库: {{ Form.storname }}</div>
          </div>

          <!-- <div style="margin-left: 10px">
            <div>供应商: {{ Form.supplier_dictText }}</div>
          </div> -->
        </div>
        <div
          id="style1"
          style="
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            height: 30px;
            line-height: 30px;
          "
        >
          <div style="margin-left: 10px">
            <div>供应商: {{ Form.supplier_dictText }}</div>
          </div>
        </div>
        <!-- 表格 -->
        <div class="print-table" style="margin-top: 5px">
          <table
            style="
              width: 100%;
              align: center;
              text-align: center;
              border-collapse: collapse;
            "
            border="0"
            cellspacing="0"
            cellpadding="0"
          >
            <tr>
              <th>存货编码</th>
              <th>存货名称</th>
              <th>单位</th>
              <th>规格</th>
              <th>数量</th>
              <th>单价</th>
              <th>金额</th>
            </tr>
            <tr v-for="(item, index) in printDataSource" :key="index">
              <th>{{ item.inventoryNo }}</th>
              <th>{{ item.inventoryName }}</th>
              <th>{{ item.unit }}</th>
              <th>{{ item.standardModel }}</th>
              <th>{{ item.quantity }}</th>
              <th>{{ item.unitPrice }}</th>
              <th>{{ item.money }}</th>
            </tr>
          </table>
        </div>

        <!-- 尾部信息 -->
        <div
          style="
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            height: 30px;
            line-height: 30px;
          "
        >
          <div style="margin-left: 15px; size: 10px">
            制单人： {{ Form.singleProducer_dictText }}
          </div>
          <div style="margin-left: 80px; size: 50px">
            审核人： {{ Form.inspector_dictText }}
          </div>
        </div>
      </div>
    </div>
  </a-card>
</template>

<script>
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口
import moment from "moment";
import axios from "axios";

import printJS from "print-js";

let columns = [
  // {
  //   title: "序号",
  //   dataIndex: "key",
  //   key: "key",
  //   align: "center",
  //   width: "80px",
  // },
  {
    title: "仓库编码",
    key: "storcode",
    dataIndex: "storcode",
    align: "center",
  },
  {
    title: "仓库名称",
    key: "storname",
    dataIndex: "storname",
    align: "center",
  },
  {
    title: "仓位",
    key: "position_dictText",
    dataIndex: "position_dictText",
    align: "center",
  },
  // {
  //   title: "库位",
  //   key: "depotLocation_dictText",
  //   dataIndex: "depotLocation_dictText",
  //   align: "center",
  // },

  // {
  //   title: "所属单位",
  //   key: "storageUnit_dictText",
  //   dataIndex: "storageUnit_dictText",
  //   align: "center",
  // },

  {
    title: "存货编码",
    dataIndex: "invcode",
    key: "invcode",
    align: "center",
  },
  {
    title: "存货名称",
    dataIndex: "invname",
    key: "invname",
    align: "center",
  },
  {
    title: "规格型号",
    dataIndex: "invspec",
    key: "invspec",
    align: "center",
  },
  {
    title: "单位",
    key: "measname",
    dataIndex: "measname",
    align: "center",
  },

  {
    title: "单价",
    key: "unitPrice",
    dataIndex: "unitPrice",
    align: "center",
  },
  {
    title: "数量",
    key: "quantity",
    dataIndex: "quantity",
    align: "center",
  },

  {
    title: "金额",
    key: "money",
    dataIndex: "money",
    align: "center",
  },
  {
    title: "扣重",
    key: "deduction",
    dataIndex: "deduction",
    align: "center",
  },
  {
    title: "源单号",
    key: "sourceNumber",
    dataIndex: "sourceNumber",
    align: "center",
  },
  {
    title: "生产日期",
    key: "productionDate",
    dataIndex: "productionDate",
    align: "center",
  },
  {
    title: "保质期(月)",
    dataIndex: "shelfLife",
    key: "shelfLife",
    align: "center",
    // scopedSlots: { customRender: "expirationTime" },
  },
  {
    title: "批次号",
    key: "batchNumber",
    dataIndex: "batchNumber",
    align: "center",
  },
  {
    title: "入库日期",
    dataIndex: "storageDate",
    key: "storageDate",
    align: "center",
    width: "5%",
    scopedSlots: { customRender: "storageDate" },
  },
  {
    title: "是否赠品",
    key: "giveaway_dictText",
    dataIndex: "giveaway_dictText",
    align: "center",
    width: "120px",
  },

  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    align: "center",
  },
];
export default {
  data() {
    return {
      u8c_array: [], //u8c传递数据表格的数据源
      arr: [], //
      arrIn: [], //
      GeneralBillVO_46: [], //需给用友传递的data
      GeneralBillVO_46In: [], //需给用友传递的data
      ayyanyany: [],
      ayyanyanyIn: [],
      dataList: [], //获取所有数据
      updateSucessRecordTag: false, //同步至u8c按钮的状态

      //保存关于反审核的信息
      isAntiAudit: [], //是否反审核
      isSynchronized: [], //是否同步
      savecoperator: "", //查询后获取操作员，删除用

      biaotouzhujian: "", //查询采购订单的表头主键

      all_list: [],

      Form: {
        id: "", // id
        document: "", // 单据号
        documentDate: "", // 单据日期
        supplier_dictText: "", //供应商
        sendReceiveType_dictText: "", // 收发类别名称
        canCheck: false,

        depotName: "", // 仓库名称
        depotNo: "", // 仓库编号
        depotId: "", // 仓库Id
        storageUnit: "", // 所属单位名称
        storageUnitId: "", // 所属单位Id
        storageUnitNo: "", // 所属单位编号
        department: "", // 部门名称
        deptId: "", // 部门id
        client: "", // 客户名称

        clientId: "", // 客户Id

        sendReceiveTypeId: "", // 收发类别Id
        responsiblePerson: "", // 负责人名称
        responsiblePersonId: "", // 负责人Id
        inspector: "", // 审核人名称
        inspectorId: "", // 审核人Id
        balance: "", // 审核日期
        singleProducer: "", // 制单人名称
        singleProducerId: "", // 制单人Id
      },
      printDataSource: [],

      saleForm: {}, //师姐用
      // 格式
      layout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 15 },
      },
      printLayout: { labelCol: { span: 5 }, wrapperCol: { span: 19 } },

      columns,
      DataSource: [],
      autoSize: {
        x: 3500,
        y: 670,
      },
      alreadyCheckTag: true, // 可以审核
      alreadyRecordTag: true, // 可以记账
    };
  },
  mounted() {
    // this.getRouterParam();
    console.log("renderData:::", this.$route);
    this.getMainListByDocment();
  },

  watch: {
    $route: function (to) {
      // if (
      //   to.path == "/ProcurementInputList" &&
      //   form.path == "/ProcurementInputDetail"
      // ) {
      // console.log("--------- 更新视图 采购入库详情  ----------");
      // this.getMainListByDocment();
      // }
      if (to.path === "/purchaseCancelDetail" && to.query?.document) {
        console.log("--------- 更新视图 采购入库详情  ----------");
        this.getMainListByDocment();
      }
    },
  },

  methods: {
    getPrint() {
      this.printDataSource = [];
      let sum = 0;
      for (let i = 0; i < this.DataSource.length; i++) {
        let data = {
          inventoryNo: this.DataSource[i].invcode,
          inventoryName: this.DataSource[i].invname,
          unit: this.DataSource[i].measname,
          standardModel: this.DataSource[i].invspec,
          quantity: this.DataSource[i].quantity,
          unitPrice: this.DataSource[i].unitPrice,
          money: this.DataSource[i].money,
        };
        sum = sum + this.DataSource[i].quantity;
        this.printDataSource.push(data);
      }

      // 计算合计
      let endData = {
        inventoryNo: "合计",
        inventoryName: "",
        unit: "",
        standardModel: "",
        quantity: sum,
        unitPrice: "",
        money: "",
      };
      this.printDataSource.push(endData);
    },

    // 打印功能实现
    goPrint() {
      const style = "@page {margin:0 10mm}; "; // 去掉页眉和页脚
      printJS({
        style, // 添加去掉页眉页脚样式
        targetStyles: ["*"],
        type: "html", // 类型
        printable: "printCons", // 表格内容
        maxWidth: 1000,
        // 表头
        header: ` 
        <h3  style="
            padding-top:10px;
            text-align: center;
            height: 40px;
            line-height: 40px;
            font-size: 20px;
          ">采购入库退库单</h3>
       `,
        // 表格属性及内容
        // properties: [
        //   { field: "inventoryNo", displayName: "存货编码", columnSize: `10%` },
        //   {
        //     field: "inventoryName",
        //     displayName: "存货名称",
        //     columnSize: `30%`,
        //   },
        //   { field: "standardModel", displayName: "规格", columnSize: `20%` },
        //   { field: "unit", displayName: "单位", columnSize: `10%` },
        //   { field: "quantity", displayName: "数量", columnSize: `10%` },
        //   { field: "remark", displayName: "备注", columnSize: `20%` },
        // ],
        // gridHeaderStyle: "border: 1px solid #000;text-align:center", // 表头公用样式
        // gridStyle: "border: 1px solid #000;text-align:center;height:20px", // 表格公用样式
        // 默认字体置中,高度20
      });
    },

    getMainListByDocment() {
      //反审核标志位重置
      this.isAntiAudit = [];
      this.isSynchronized = [];

      let _query = "";
      const document = this.$route.query.document;
      const id = this.$route.query.id;

      // if (document.length < 1) return;
      const auditMark = this.$route.query.auditMark;
      _query += "?pageSize=500&inOutIdentification=3"; // 内容数量 入库
      _query += `&id=${id}`;

      _query += `&auditMark=${auditMark}`; // 未审核:2 审核：1
      _query += `&document=${document}`;
      // queryPath += _query + queryPath;
      comHttp.getInOrOutStorageOrderAndGoodsList(_query).then((res) => {
        this.DataSource = [];
        console.log("1111111111", res);
        let _data = res.result.records;
        let firstData = _data[0];

        //反审核标志位
        for (let i = 0; i < _data.length; i++) {
          let data = _data[i].isAntiAudit;
          let data2 = _data[i].isSynchronized;
          this.isAntiAudit.push(data);
          this.isSynchronized.push(data2);
        }
        console.log(" this.isAntiAudit", this.isAntiAudit);
        console.log(" this.isSynchronized", this.isSynchronized);

        if (auditMark == 2) {
          console.log(firstData.inspector);
          console.log(this.$store.state.user.info.id);
          if (firstData.inspector == this.$store.state.user.info.id) {
            // 审核人 == 当前登录人
            this.Form.canCheck = true;
          } else {
            this.Form.canCheck = false;
          }
        } else {
          this.Form.canCheck = false;
        }

        // if (firstData.cwhsmanagerid) {
        //   let kuguanyaun = firstData.cwhsmanagerid.split("|");
        //   this.Form.cwhsmanagerid = kuguanyaun[1]; // 库管员
        // }

        // 公共部分
        this.Form.cwhsmanagerid = firstData.cwhsmanagerid_dictText;
        this.Form.id = firstData.id;
        this.Form.document = firstData.document; // 单据号
        this.Form.documentDate = firstData.documentDate; // 单据日期
        this.Form.sendReceiveType_dictText = firstData.sendReceiveType_dictText; // 收发类型
        this.Form.pkCalbodyByCode = firstData.pkCalbodyByCode; // 收发类型
        this.Form.cbiztype_dictText = firstData.cbiztype_dictText; // 业务类型

        this.Form.supplier_dictText = firstData.supplier_dictText; //供应商
        this.Form.singleProducer_dictText = firstData.singleProducer_dictText; // 制单人
        this.Form.responsiblePerson_dictText =
          firstData.responsiblePerson_dictText; // 负责人this.Form.
        this.Form.inspector_dictText = firstData.inspector_dictText; // 审核人
        this.Form.balance = firstData.balance;
        this.Form.storname = firstData.storname; //table里面的仓库名称

        _data.forEach((item, index) => {
          item.key = index + 1;
        });
        console.log("2222222", this.DataSource);

        this.DataSource = _data;
        this.getPrint();

        //根据id 查采购入库单
        this.getSaleInfoById(_data[0].saleOrderAddId);
        this.dataList = res.result.records;
        console.log("this.dataList", this.dataList);

        // 传递单据给用友需要的数据
        this.sortArr(this.DataSource, "depotNo");
      });
    },
    //根据保存的saleOrderAddId 查询
    getSaleInfoById(id) {
      comHttp.getpurchaseaddorder("?id=" + id).then((res) => {
        console.log(111111111111111111111, "res");
        this.saleForm = res.result.object; //师姐用
        console.log("this.saleForm", this.saleForm);
        for (let i = 0; i < this.DataSource.length; i++) {
          res.result.object.purchaseItemInformationList.forEach((element) => {
            if (element.inventoryNo == this.DataSource[i].invcode) {
              this.$set(this.DataSource[i], "ntaxrate", element.ntaxrate);
              this.$set(
                this.DataSource[i],
                "amountOfMoney",
                element.amountOfMoney
              );
              this.$set(
                this.DataSource[i],
                "ntaxpricemny",
                element.ntaxpricemny
              );
              this.$set(
                this.DataSource[i],
                "currencytypeid",
                element.currencytypeid
              );
              this.$set(
                this.DataSource[i],
                "currencytypeid_dictText",
                element.currencytypeid_dictText
              );
            }
          });
        }
      });
      console.log(this.DataSource, "datasource");
    },
    // 审核函数
    Examine() {
      let option = {
        id: this.Form.id,
        balance: this.Form.balance,
        auditMark: 1,
      };
      // this.Form.balance = moment().format("YYYY-MM-DD");

      console.log(option);

      // 提交审核信息，修改表一数据
      comHttp.updateInOrOutStorageOrder(option).then((res) => {
        if (res.success) {
          this.$message.success(`审核成功`);
          this.Form.canCheck = false;

          // this.getMainListByDocment();

          // 跳转回列表页面
          this.$router.push("/purchaseCancelList");
        } else {
          this.$message.success(`审核失败`);
        }
      });
    },

    // 提交
    Submit() {},
    // 获取路由跳转参数
    getRouterParam() {
      console.log("查询参数:::", this.$route.query.Id);

      // 通过出入库id 查询出入库信息
      if (typeof this.$route.query.Id == "undefined") {
        console.log("常规跳转");
      } else {
        this.setInitInfo(this.$route.query.Id);
      }
    },
    //todo 点击反审核
    //! 反审核
    async No_Examine() {
      console.log(this.isSynchronized[0], "this.isSynchronized[0]");
      if (this.isSynchronized[0] == "已同步") {
        // fbillflag 单据状态 1删除 2自由(缺省) 3库房签字 4存货系统审核
        let _data = await this.purchaseInSign();
        console.log("_data", _data);
        // 使用 JSON.parse() 方法将数据转换为 JavaScript 对象。
        let flag = JSON.parse(_data.data).datas[0].parentvo.fbillflag;
        //查询后获取操作员，删除用
        this.savecoperator = JSON.parse(
          _data.data
        ).datas[0].parentvo.operator_code;
        console.log("查询后获取操作员，删除用", this.savecoperator);

        if (_data.status == "success") {
          if (flag == "4") {
            this.$message.error("已签字，反审核失败！");
          } else {
            // 查询成功后进行采购入库单的删除
            let _deleteFlag = await this.deletePurchaseIn();
            console.log("_deleteFlag", _deleteFlag);
            if (_deleteFlag == "success") {
              console.log("入库单删除成功");
              this.$message.success("反审核成功");
              // 采购入库单删除成功后进行采购订单的反审核
              let _unapproveFlag = await this.orderUnapprove();

              if (_unapproveFlag == "success") {
                //!我方反审核 todo
                //如果弃审成功 就走更新是否同步字段为"未同步"
                this.postSynchronized("未同步");
                //如果弃审成功 就走更新是否反审核成功得标识
                this.update_audit("已反审核");
                //如果弃审成功 就走更新是否审核标识
                this.update_Mark(2);

                // 跳转回列表页面
                this.$router.push("/purchaseCancelList");
              }
            }
          }
        }
      } else {
        this.$message.success("未同步至用友，即将进行我方数据库反审核功能");
        //未同步至用友 直接进行反审核
        this.postSynchronized("未同步");
        this.update_audit("已反审核");
        this.update_Mark(2);

        // 跳转回列表页面
        this.$router.push("/purchaseCancelList");
      }
    },
    // !采购入库单查询
    purchaseInSign() {
      // u8c接口
      return new Promise((resolve) => {
        axios({
          headers: {
            "Access-Control-Allow-Origin": "*",
            trantype: "code",
            "Content-Type": "application/json",
            usercode: "13355262265",
            password: "5ef208ee90e5504a7b569ebbd6342634",
            system: "test",
          },
          method: "post",
          url: "/api/u8cloud/api/ic/purchasein/query",
          data: {
            billcode: this.Form.document, //单据号
            corp: "1001", //公司
            date_begin: this.Form.documentDate, //起始日期
            date_end: this.Form.documentDate, //结束日期
            inventory: "", //存货
            page_now: "1", //起始页
            warehouse: "", //仓库//! 不传了
          },
        }).then((response) => {
          resolve(response.data);
          console.log("返回的数据为::::", response.data);

          if (response.data.status == "success") {
            // this.$message.success("查询成功");
            console.log("查询成功");
          } else {
            this.$message.error(response.data.errormsg);
          }
        });
      });
    },
    //! 调用用友采购入库单删除接口
    deletePurchaseIn() {
      return new Promise((resolve) => {
        axios({
          headers: {
            "Access-Control-Allow-Origin": "*",
            trantype: "code",
            "Content-Type": "application/json",
            usercode: "13355262265",
            password: "5ef208ee90e5504a7b569ebbd6342634",
            system: "test",
          },
          method: "post",
          url: "/api/u8cloud/api/ic/purchasein/delete",
          data: {
            queryInfo: {
              billcode: this.Form.document,
              date_begin: this.Form.documentDate,
              date_end: this.Form.documentDate,
              corp: "1001",
            },
            deleteInfo: {
              coperator: this.savecoperator,
            },
          },
        }).then((response) => {
          resolve(response.data.status);
          if (response.data.status == "success") {
            // this.$message.success("用友删除成功");
          } else {
            this.$message.error(response.data.errormsg);
          }
        });
      });
    },
    // ! 采购订单弃审
    orderUnapprove() {
      return new Promise((resolve) => {
        axios({
          headers: {
            "Access-Control-Allow-Origin": "*",
            trantype: "code",
            "Content-Type": "application/json",
            usercode: "13355262265",
            password: "5ef208ee90e5504a7b569ebbd6342634",
            system: "test",
          },
          method: "post",
          url: "/api/u8cloud/api/pu/order/unapprove",
          data: {
            queryinfo: {
              code: this.Form.document,
              date_begin: this.Form.documentDate,
              date_end: this.Form.documentDate,
              corp: "1001",
            },
            approveinfo: {
              // date_delete: `${moment().format("YYYY-MM-DD")}`,
              approvid: "17864817161",
              status: "R",
            },
          },
        }).then((response) => {
          resolve(response.data.status);
          if (response.data.status == "success") {
            console.log("弃审成功");
          } else {
            this.$message.error(response.data.errormsg);
          }
        });
      });
    },
    //点击同步至用友
    handleSaveButton() {
      if (this.isAntiAudit[0] == "已反审核") {
        console.log(" --- 触发修改 ---");
        this.update_u8c();
        return;
      }
      console.log(" --- 触发新增 ---");

      this.save_u8c();
    },
    //! 同步至用友得修改接口
    async update_u8c() {
      let _data = await this.searchcorderid();
      // 使用 JSON.parse() 方法将数据转换为 JavaScript 对象。
      const flag = JSON.parse(_data.data).datas[0].parentvo.corderid;
      // u8c接口
      this.ayyanyany = [];
      //todo:已审核后才可以调用
      if (this.dataList[0].auditMark_dictText == "已审核") {
        // ==========同步至采购订单=========
        for (let i = 0; i < this.u8c_array.length; i++) {
          this.arr = [];
          for (let j = 0; j < this.u8c_array[i].length; j++) {
            let data = {
              cbaseid: this.u8c_array[i][j].invcode, //存货基本id√
              cmangid: this.u8c_array[i][j].invcode, //存货管理id√
              nordernum: this.u8c_array[i][j].quantity, //订货数量√
              corderid: flag, //采购订单主表主键√
              corder_bid: "", //采购订单子表主键√
              cwarehouseid: this.u8c_array[i][j].storcode, //收货仓库√
              pk_arrvcorp: "1001", // 收货公司
              pk_corp: "1001", //公司编码
              blargess:
                this.u8c_array[i][j].giveaway_dictText == "是" ? "Y" : "N", //是否赠品√
              ntaxrate: `${this.u8c_array[i][j].ntaxrate * 100}`, // 税率
              cusedeptid: "", // 使用部门
              ccurrencytypeid: this.u8c_array[i][j].currtypecode, // 币种id
              nexchangeotobrate: "", // 折本汇率√
              noriginalcurprice: "", //原币无税单价=含税单价/（1+税率）√
              norgtaxprice: "", // 原币含税单价√
              noriginaltaxpricemny: this.u8c_array[i][j].amountOfMoney, //原币价税合计√
              ntaxmny: "", // 本币税额√
              nmoney: "", // 本币金额√
              ntaxpricemny: this.u8c_array[i][j].ntaxpricemny, // 本币价税合计√
            };
            this.arr.push(data);
          }
          this.GeneralBillVO_46 = {
            parentvo: {
              pk_corp: "1001", //公司编码√
              cvendormangid: this.u8c_array[i][0].supplierByCode_dictText, //!供应商管理√
              cpurorganization: "1000", //采购组织√kandao
              corderid: flag, //订单主表主键√
              cbiztype: this.u8c_array[i][0].cbiztypeByCode_dictText, //业务流程√
              cdeptid: this.saleForm.cdeptidNo, //采购部门
              coperator: this.u8c_array[i][0].singleProducerByCode, //制单人id√
              cemployeeid: this.saleForm.buyerNo, //采购员
              dorderdate: moment(this.u8c_array[i][0].documentDate).format(
                "YYYY-MM-DD"
              ), //订单日期√
              vordercode: this.u8c_array[i][0].document, //单据号
              vdef1: this.u8c_array[i][0].sendReceiveType1_dictText, //自定义项1--收发类别要传编码 此次传的是名称
              breturn: "N", //是否退货
            },
            childrenvo: this.arr,
          };
          this.ayyanyany.push(this.GeneralBillVO_46);
        }
        // u8c接口
        axios({
          headers: {
            "Access-Control-Allow-Origin": "*",
            trantype: "code",
            "Content-Type": "application/json",
            usercode: "13355262265",
            password: "5ef208ee90e5504a7b569ebbd6342634",
            system: "test",
          },
          method: "post",
          url: "/api/u8cloud/api/pu/order/update",
          data: {
            puordervo: this.ayyanyany,
          },
        }).then((response) => {
          console.log("返回的数据为::::", response.data);
          if (response.data.status == "success") {
            // this.$message.success("同步成功");
            //调用采购订单审批接口就可以继续反审核了（否则不能再次反审核）
            this.update_u8c_approve();

            this.updateSucessRecordTag = true;
          } else {
            this.$message.error(response.data.errormsg);
          }
        });
      } else {
        this.$message.error("请先审核，再进行同步！");
      }
    },
    //! 调用采购订单审批接口就可以继续反审核了（否则不能再次反审核）
    update_u8c_approve() {
      axios({
        headers: {
          "Access-Control-Allow-Origin": "*",
          trantype: "code",
          "Content-Type": "application/json",
          usercode: "13355262265",
          password: "5ef208ee90e5504a7b569ebbd6342634",
          system: "test",
        },
        method: "post",
        url: "/api/u8cloud/api/pu/order/approve",
        data: {
          queryinfo: {
            date_end: this.Form.documentDate,
            date_begin: this.Form.documentDate,
            code: [this.Form.document],
            corp: "1001",
          },
          approveinfo: {
            approvid: "17864817161",
          },
        },
      }).then((response) => {
        if (response.data.status == "success") {
          // this.$message.success("采购订单审批成功");//todo 这个提示是准确的，下面的是用来提示的
          this.$message.success("同步成功");
          //同步至用友成功以后调用我们的接口修改同步字段为“已同步”
          this.postSynchronized("已同步");
          //如果弃审成功 就走更新是否反审核成功得标识
          this.update_audit("未反审核");

          // 跳转回列表页面
          this.$router.push("/purchaseCancelList");
        } else {
          this.$message.error(response.data.errormsg);
        }
      });
    },
    //! 查询出表头主键
    searchcorderid() {
      return new Promise((resolve) => {
        axios({
          headers: {
            "Access-Control-Allow-Origin": "*",
            trantype: "code",
            "Content-Type": "application/json",
            usercode: "13355262265",
            password: "5ef208ee90e5504a7b569ebbd6342634",
            system: "test",
          },
          method: "post",
          url: "/api/u8cloud/api/pu/order/query",
          data: {
            date_end: this.Form.documentDate,
            page_size: 10,
            page_now: 1,
            date_begin: this.Form.documentDate,
            code: this.Form.document,
            corp: "1001",
          },
        }).then((response) => {
          resolve(response.data);
          // console.log("response",response.data.datas[0].parentvo.corderid);
          if (response.data.status == "success") {
            this.$message.success("查询成功");
            // 使用 JSON.parse() 方法将数据转换为 JavaScript 对象。
            let flag = JSON.parse(response.data).datas[0].parentvo.corderid;
            this.biaotouzhujian = flag;
            console.log("this.biaotouzhujian", this.biaotouzhujian);
          } else {
            this.$message.error(response.data.errormsg);
          }
        });
      });
    },

    // 用友单据传递
    // 用友单据传递
    save_u8c() {
      this.ayyanyany = [];
      console.log(this.saleForm, "this.saleForm");
      //todo:已审核后才可以调用
      if (this.dataList[0].auditMark_dictText == "已审核") {
        // ==========同步至采购订单=========
        for (let i = 0; i < this.u8c_array.length; i++) {
          console.log("i", i);

          this.arr = [];

          for (let j = 0; j < this.u8c_array[i].length; j++) {
            console.log("j", j);
            console.log("this.u8c_array[i]", this.u8c_array[i]);
            let data = {
              cbaseid: this.u8c_array[i][j].invcode, //存货基本id√
              cmangid: this.u8c_array[i][j].invcode, //存货管理id√
              nordernum: -this.u8c_array[i][j].quantity, //订货数量√
              corderid: this.u8c_array[i][j].otherId, //采购订单主表主键√
              corder_bid: this.u8c_array[i][j].id, //采购订单子表主键√
              cwarehouseid: this.u8c_array[i][j].storcode, //收货仓库√
              pk_arrvcorp: "1001", // 收货公司
              pk_corp: "1001", //公司编码
              blargess:
                this.u8c_array[i][j].giveaway_dictText == "是" ? "Y" : "N", //是否赠品√
              ntaxrate: `${this.u8c_array[i][j].ntaxrate}`, // 税率
              cusedeptid: "", // 使用部门
              ccurrencytypeid: this.u8c_array[i][j].currtypecode, // 币种id
              nexchangeotobrate: "", // 折本汇率√
              noriginalcurprice: "", //原币无税单价=含税单价/（1+税率）√
              norgtaxprice: this.u8c_array[i][j].unitPrice, // 原币含税单价√
              noriginaltaxpricemny: this.u8c_array[i][j].amountOfMoney, //原币价税合计√
              ntaxmny: "", // 本币税额√
              nmoney: "", // 本币金额√
              ntaxpricemny: this.u8c_array[i][j].ntaxpricemny, // 本币价税合计√
            };
            this.arr.push(data);
            console.log("this.arr", this.arr);
          }
          this.GeneralBillVO_46 = {
            parentvo: {
              breturn: "Y", //是否退货
              pk_corp: "1001", //公司编码√
              cvendormangid: this.u8c_array[i][0].supplierByCode_dictText, //!供应商管理√
              cpurorganization: "1000", //采购组织√kandao
              corderid: this.Form.id, //订单主表主键√
              cbiztype: this.u8c_array[i][0].cbiztypeByCode_dictText, //业务流程√
              cdeptid: this.saleForm.cdeptidNo || "10000002", //采购部门
              coperator: this.u8c_array[i][0].singleProducerByCode, //制单人id√
              cemployeeid: this.saleForm.buyerNo, //采购员
              dorderdate: moment(this.u8c_array[i][0].documentDate).format(
                "YYYY-MM-DD"
              ), //订单日期√
              vordercode: this.u8c_array[i][0].document, //单据号
              vdef1: this.u8c_array[i][0].sendReceiveType1_dictText, //自定义项1--收发类别要传编码 此次传的是名称
            },
            childrenvo: this.arr,
          };
          this.ayyanyany.push(this.GeneralBillVO_46);
          console.log("this.arr", this.arr);
        }
        // u8c接口
        axios({
          headers: {
            "Access-Control-Allow-Origin": "*",
            trantype: "code",
            "Content-Type": "application/json",
            usercode: "13355262265",
            password: "5ef208ee90e5504a7b569ebbd6342634",
            system: "test",
          },
          method: "post",
          url: "/api/u8cloud/api/pu/order/saveapprove",
          data: {
            puordervo: this.ayyanyany,
          },
        }).then((response) => {
          console.log("返回的数据为::::", response.data);
          if (response.data.status == "success") {
            this.$message.success("同步成功");
            this.updateSucessRecordTag = true;
            //同步至用友成功以后调用我们的接口修改同步字段为“已同步”
            this.postSynchronized("已同步");

            // 跳转回列表页面
            this.$router.push("/purchaseCancelList");
          } else {
            this.update_u8c(); //todo 新增失败的话尝试走一下修改， 这个功能还需要再完善，因为这样不会返回失败的信息。
            //todo 这里要解决一个问题： 反审核完成之后进来这个页面，是已经第二次同步了，已经不是新增了，但是根据其余的标志位无法进行判断是新增还是修改
            // this.$message.error(response.data.errormsg);
          }
        });
      } else {
        this.$message.error("请先审核，再进行同步！");
      }
    },
    //! 第一步 同步至用友成功以后调用我们的接口修改同步字段为“已/未同步”
    //是否同步标志位
    postSynchronized(isOrNo) {
      let data = {
        id: this.Form.id,
        isSynchronized: isOrNo,
      };
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res);
      });
    },
    //是否反审核标志位
    update_audit(isOrNo) {
      let data = {
        id: this.Form.id,
        isAntiAudit: isOrNo,
      };
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res);
      });
    },
    //审核标志位
    update_Mark(isOrNo) {
      let data = {
        id: this.Form.id,
        auditMark: isOrNo,
      };
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res);
      });
    },
    //TODO:获取数据
    // 路由跳转,设置初始化信息
    setInitInfo(id) {
      console.log("调用了这个函数1");
      comHttp
        .getInOrOutStorageOrderAndGoodsInfoById("?id=" + id)
        .then((res) => {
          console.log("通过Id查询出来的信息::::", res);
          // 是否审核
          if (res.result.list[0].auditMark == 1) {
            this.alreadyCheckTag = false;
          } else {
            this.alreadyCheckTag = true;
          }

          // 是否记账
          if (res.result.list[0].bookkeepingMark == 1) {
            this.alreadyRecordTag = false;
          } else {
            this.alreadyRecordTag = true;
          }

          this.otherId = res.result.list[0].otherId; // 表一 Id
          this.Form = {
            id: res.result.list[0].otherId, // 表一 Id
            document: res.result.list[0].document, // 单据号
            documentDate: res.result.list[0].documentDate, // 单据日期
            department: res.result.list[0].deptId_dictText, // 销售部门
            sendReceiveType: res.result.list[0].sendReceiveType, // 收发类别
            responsiblePerson: res.result.list[0].responsiblePerson_dictText, // 负责人
            inspector: res.result.list[0].inspector_dictText, // 审核人
            singleProducer: res.result.list[0].singleProducer_dictText, // 制单人
            balance: res.result.list[0].balance, //审核日期
          };
          this.DataSource = [];
          for (let i = 0; i < res.result.list.length; i++) {
            let data = {
              key: i + 1,
              id: res.result.list[i].twoId, // 表二Id
              otherId: res.result.list[i].otherId,
              depotNo: res.result.list[i].depotId, // 仓库编码
              depotName: res.result.list[i].depotId_dictText, // 仓库名称
              depotLocation: res.result.list[i].depotLocation, // 库位
              position: res.result.list[i].position, // 仓位
              unitPrice: res.result.list[i].unitPrice, //单价
              deduction: res.result.list[i].deduction, //扣重
              productionDate: res.result.list[i].productionDate, //生产日期
              storageDate: res.result.list[i].storageDate, //入库日期
              money: res.result.list[i].money, //金额
              // auxiliaryUnit: res.result.list[i].auxiliaryUnit, // 辅助单位
              storageUnit: res.result.list[i].storageUnit_dictText, // 所属单位
              inventoryNo: res.result.list[i].inventoryNo, // 存货编码
              inventoryName: res.result.list[i].inventoryId_dictText, // 存货名称
              invspec: res.result.list[i].invspec, // 规格型号
              measname: res.result.list[i].measname, // 单位
              //保质期
              // auxiliaryUnit: res.result.list[i].auxiliaryUnit, // 辅助单位
              quantity: res.result.list[i].quantity, // 数量
              sourceNumber: res.result.list[i].sourceNumber, // 源单单号
              batchNumber: res.result.list[i].batchNumber, // 批次号
              giveaway: res.result.list[i].giveaway_dictText, // 是否赠品
              // productionDate: res.result.list[i].productionDate, // 出库日期
              remark: res.result.list[i].remark, // 备注
            };
            this.DataSource.push(data);
          }
          console.log("这是DataSource", this.DataSource);
          // this.getPrint();
          console.log("表格信息:::::", this.DataSource);
        });
    },

    // this.u8c_array数组根据仓库编码筛选，将相同的仓库编码放在一个数组里
    sortArr(arr, str) {
      var newArr = [],
        newArrItem = [],
        // 临时变量
        tempArr = [];
      // 按照特定的参数将数组排序将具有相同值的排在一起
      arr = arr.sort(function (a, b) {
        var s = a[str],
          t = b[str];

        return s < t ? -1 : 1;
      });

      if (arr.length) {
        tempArr = arr[0][str];
      }

      // 将相同类别的对象添加到统一个数组
      for (var i in arr) {
        if (arr[i][str] === tempArr) {
          console.log("tempArr", tempArr);
          newArrItem.push(arr[i]);
        } else {
          tempArr = arr[i][str];
          newArr.push(newArrItem);
          newArrItem = [arr[i]];
        }
      }

      // 将最后的内容推出新数组
      newArr.push(newArrItem);
      this.u8c_array = newArr;
      console.log("u8c_arr", this.u8c_array);
    },
  },
};
</script>

<style>
.print-table table td,
.print-table table th,
.print-table table tr {
  border: 1px solid black;
}
.print-table table tr {
  height: 30px;
}
.print-table table th {
  height: 30px;

  font-weight: normal;
}
</style>
